package com.shopcart.servlet;

import java.io.IOException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shopcart.controller.CustomerController;
import com.shopcart.entity.Customer;

@WebServlet("/ItemWarnServlet")
public class ItemWarnServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ItemWarnServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Long productId = Long.valueOf(request.getParameter("id"));
		HttpSession session = request.getSession();

		Customer customer = (Customer) session.getAttribute("customer");

		CustomerController customerController = null;
		Context ctx = null;
		try {
			ctx = new InitialContext();
			customerController = (CustomerController) ctx.lookup("ejb/CustomerControllerBean");
		} catch (NamingException e) {
			e.printStackTrace();
		}

		customer = customerController.addNotExistingProduct(customer, productId);
		//session.setAttribute("customer", customer);
		
		try {
			ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/ConnectionFactory");
			Queue queue = (Queue) ctx.lookup("jms/Queue");
			Connection conn = connectionFactory.createConnection();
			Session jmsSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			MapMessage msg = jmsSession.createMapMessage();
			msg.setLong("productId", productId);
			msg.setInt("productCount", 10);
			MessageProducer mp = jmsSession.createProducer(queue);
			mp.send(msg);
			jmsSession.close();
			conn.close();
		} catch (JMSException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
}